"use strict";

module.exports = core;

const semver = require("semver");
const colors = require("colors");
const homedir = require("os").homedir();
const pathExist = require("path-exists").sync;
const path = require("path");
const commander = require("commander");

let args;
let config;

const program = new commander.Command();

const pkg = require("../package.json");
// checkInputArgs();
const log = require("@dmcy-cli-dev/log");
const constant = require("../lib/const");

async function core() {
  try {
    checkPkgVersion();
    checkNodeVersion();
    checkRoot();
    checkUserHome();
   // checkInputArgs();
    checkEnv();
    await checkGlobalUpdate();
    registerCommand();
  } catch (e) {
    log.error(e.message);
  }
}

function checkPkgVersion() {
 // log.notice("cli", pkg.version);
}

function checkNodeVersion() {
  //获取当前node版本号
  const currentVersion = process.version;
  const lowestNodeVersion = constant.LOWEST_NODE_VERSION;
  // console.log('test',currentVersion,lowestNodeVersion);
  //比对node版本号
  if (semver.gtr(lowestNodeVersion, currentVersion)) {
    throw new Error(
      colors.red(`dmcy-cli-dev需要安装v${lowestNodeVersion}及以上版本`)
    );
  }
}

function checkRoot(){
  const rootCheck = require('root-check');
  rootCheck();
}

function checkUserHome(){
  if(!homedir || !pathExist(homedir)){
    throw new Error(colors.red('当前用户主目录不存在'));
  }
}

function checkInputArgs(){
  const minimist = require("minimist");
  args = minimist(process.argv.slice(2));
  checkArgs();
}

function checkArgs(){
  if(args?.debug){
    process.env.LOG_LEVEL = "verbose";
  }
  else{
    process.env.LOG_LEVEL = "info";
  }
  log.level = process.env.LOG_LEVEL;
}

function checkEnv(){
  const dotenv = require("dotenv");
  const dotenvPath = path.resolve(homedir,".env");
  if(pathExist(dotenvPath)){
     dotenv.config({
      path:dotenvPath
    });
  }
  createDefaultConfig();
  log.verbose("环境变量",process.env.CLI_HOME_PATH);
}

function createDefaultConfig(){
  const cliConfig = {
    home:homedir
  }
  if(process.env.CLI_HOME){
    cliConfig.home = path.join(homedir,process.env.CLI_HOME);
  }
  else{
    cliConfig.home = path.join(homedir,constant.DEFAULT_CLI_HOME);
  }
  process.env.CLI_HOME_PATH = cliConfig.home;
  //return cliConfig;
}

async function checkGlobalUpdate(){
  //1.获取当前的版本号和模块名
  const currentVersion = pkg.version;
  const npmName = pkg.name;
  const { getNpmSemverVersion } =  require("@dmcy-cli-dev/get-npm-info");
  const lastVersion = await getNpmSemverVersion(currentVersion,npmName)
  if(lastVersion && semver.lt(currentVersion,lastVersion)){
    log.warn("更新提示",colors.yellow(`清手动更新${npmName},当前版本:${currentVersion},最新版本:${lastVersion},更新命令：npm install ${npmName} -g`));
  }
  //2.调用npm API，获取所有版本号
  //3.提取所有版本号，比对哪些版本号是大于当前版本号
  //4.获取最新的版本号，提示用户更新到该版本
}

//2023/04/18

function registerCommand(){
  //注册版本号
  program.name(Object.keys(pkg.bin)[0])
  .usage("<command> [options]")
  .version(pkg.version)
  .option("-d,--debug","是否开启调试模式",false);

  program.on("option:debug",function()=>{
    if(program.debug){
      process.env.LOG_LEVEL = "verbose";
    }
    else{
      process.env.LOG_LEVEL = "info";
    }
    log.level = process.env.LOG_LEVEL="info"
    log.verbose("test")
  })

  program.parse(process.argv);
}